package com.lagou.handle;

import com.alibaba.fastjson.JSON;
import com.lagou.util.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class ClientHandle extends ChannelInboundHandlerAdapter implements Callable {

    private String result;
    private String param;
    private RpcRequest request;
    private ChannelHandlerContext context;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive");
        this.context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取服务端响应数据
        System.out.println("服务端响应结果为："+ JSON.toJSONString(msg));
        this.result = msg.toString();
        notify();
    }

    /**
     * 向服务端发送请求，开始等待唤醒
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        System.out.println("客户端发送请求。。。。"+ JSON.toJSONString(this.request));
        context.writeAndFlush(this.request);
        wait();
        return result;
    }

    public void setParam(String param){
        this.param = param;
    }

    public void setRequest(RpcRequest request){
        this.request = request;
    }
}
